package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.Dish;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderManageService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderManageServiceImpl implements OrderManageService {

    private static final Integer PENDING_ORDERS = 3;
    private static final Integer TO_BE_DELIVERED = 2;
    private static final Integer DELIVERY_IN_PROGRESS = 4;


    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    SetmealMapper setmealMapper;
    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO orderCount() {

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        List<Integer> status = new ArrayList<>();

        Collections.addAll(status,PENDING_ORDERS,TO_BE_DELIVERED,DELIVERY_IN_PROGRESS);

        for (Integer statu : status) {

            Integer orderCount = ordersMapper.getOrdersCount(statu);

            if(statu.equals(PENDING_ORDERS)){

                orderStatisticsVO.setConfirmed(orderCount);

            }else if(statu.equals(TO_BE_DELIVERED)){

                orderStatisticsVO.setToBeConfirmed(orderCount);

            }else {

                orderStatisticsVO.setDeliveryInProgress(orderCount);
            }

        }
        return orderStatisticsVO;
    }

    /**
     * 订单搜索
     * @param dto
     * @return
     */
    @Override
    public PageResult orderSearch(OrdersPageQueryDTO dto) {

        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<OrderVO> orders = ordersMapper.getOrders(dto);

        List<Long> orderIds = orders.getResult().stream().map(Orders::getId).collect(Collectors.toList());

        int index=0;
        for (Long orderId : orderIds) {

            StringBuilder orderDishes = new StringBuilder();

            List<OrderDetail> orderDetails = orderDetailMapper.getorderDetailById(orderId);

            for (OrderDetail detail : orderDetails) {

                orderDishes.append(detail.getName()+"*"+detail.getNumber()+";");

            }
            orders.getResult().get(index++).setOrderDishes(orderDishes.toString());

        }
        return new PageResult(orders.getTotal(),orders.getResult());
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetails(Long id) {

        OrderVO orderVO = ordersMapper.getOrdersById(id);

        List<OrderDetail> orderDetail = orderDetailMapper.getOrderDetails(id);

        StringBuilder orderDishes = new StringBuilder();

        for (OrderDetail detail : orderDetail) {

            Dish dish = dishMapper.getDishById(detail.getDishId());

            SetmealVO setmeal = setmealMapper.getSetmealById(detail.getSetmealId());
            if(dish!=null){
                orderDishes.append(dish.getName());
            }
            if(setmeal!=null){
                orderDishes.append(setmeal.getName());
            }

        }
        orderVO.setOrderDetailList(orderDetail);
        orderVO.setOrderDishes(orderDishes.toString());
        return orderVO ;
    }
    /**
     * 派送订单
     * @param id
     *
     */
    @Override
    public void deliveryOrder(Long id) {
        //接单后更新估计送达时间
        //更新订单状态
        ordersMapper.deliveryOrder(id);
    }
    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        //更新状态为已完成

        ordersMapper.completeOrder(id);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        List<OrderDetail> orderDetails = new ArrayList<>();
        orderDetails = orderDetailMapper.getById(id);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail: orderDetails) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, cart, "productId:itemId", "quantity:count");
            shoppingCarts.add(cart);
        }
        for (ShoppingCart shoppingCart: shoppingCarts) {
            log.info("{}", shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.addShoppingCartById(shoppingCart);
        }
    }

    /**
     * 取消订单
     * @param dto
     */
    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        //取消订单需要判断用户是否付款，付款了就要退款
        //管理端取消订单默认退款
        //更新订单状态为已经退款

        //进行退款逻辑

        Orders orders = new Orders().builder()
                .id(dto.getId())
                .status(Orders.CANCELLED)
                .cancelReason(dto.getCancelReason())
                .payStatus(Orders.REFUND)
                .cancelTime(LocalDateTime.now()).build();
        ordersMapper.updateOrder(orders);
    }

    /**
     * 接收订单
     * @param dto
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO dto) {
        Orders orders = new Orders().builder()
                .id(dto.getId())
                .status(Orders.CONFIRMED)
                .checkoutTime(LocalDateTime.now()).build();
        ordersMapper.updateOrder(orders);
    }

    /**
     * 拒绝订单
     * @param dto
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO dto) {
        Orders orders = new Orders().builder()
                .id(dto.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(dto.getRejectionReason()).build();
         ordersMapper.updateOrder(orders);
        //拒绝之后退款
        //将订单信息pays status更新为 2
    }

}
